The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
In [1]:
from sympy import isprime
def right_truncatable(p = 0):
if p == 0:
for p in [2, 3, 5, 7]:
for q in right_truncatable(p):
yield q
elif isprime(p):
yield p
p *= 10
for d in (1, 3, 7, 9):
for q in right_truncatable(p+d):
yield q
def left_truncatable(p):
N = 10 ** (len(str(p))-1)
while p > 9:
p %= N
if not isprime(p):
return False
N //= 10
return True
print(sum([p for p in right_truncatable() if p > 9 and left_truncatable(p)]))
In [ ]: